package com.nicolascarrascob.clientesoap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.JsonObject;

public class UpdatePaciente extends Activity {
	private String URL = Constantes.HOST
			+ "/ServicioWebClinica/services/FichaPacienteORMWS";
	private String NAMESPACE = "http://ws";

	Paciente paciente;
	EditText runEditText;
	EditText nombreEditText;
	EditText direccionEditText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_paciente);
		runEditText = (EditText) findViewById(R.id.textRunAc);
		nombreEditText = (EditText) findViewById(R.id.textNombreAc);
		direccionEditText = (EditText) findViewById(R.id.textDireccionAc);
		new ObtenerCamposBackground().execute();
	}

	public void guardarPaciente(View v) {
		// System.out.println(paciente.getId());
		JsonObject jsonObjectPaciente = new JsonObject();
		jsonObjectPaciente.addProperty("id", paciente.getId());
		jsonObjectPaciente.addProperty("run", runEditText.getText().toString());
		jsonObjectPaciente.addProperty("nombre", nombreEditText.getText()
				.toString());
		jsonObjectPaciente.addProperty("direccion", direccionEditText.getText()
				.toString());

		Log.d("", jsonObjectPaciente.toString());
		new UpdatePacienteBackground().execute(jsonObjectPaciente.toString());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_update_paciente, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.remove_paciente:
			Log.d("", "" + paciente.getId());
			new RemovePacienteBackground().execute((paciente.getId()));
			return true;
		default:
			return true;
		}
	}

	class ObtenerCamposBackground extends
			AsyncTask<Void, Void, HashMap<String, String>> {

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(UpdatePaciente.this,
					"Clinica del Sur",
					"Espere mientras se obtienen los datos...", true);
			super.onPreExecute();
		}

		@Override
		protected HashMap<String, String> doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		protected void onPostExecute(HashMap<String, String> result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			paciente = (Paciente) getIntent().getExtras().getSerializable(
					"paciente");
			Log.d("", paciente.toString());
			runEditText.setText(paciente.getRun() + "");
			nombreEditText.setText(paciente.getNombre());
			direccionEditText.setText(paciente.getDireccion());
		}

	}

	class UpdatePacienteBackground extends AsyncTask<String, Void, String> {

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(UpdatePaciente.this,
					"Clinica del Sur",
					"Espere mientras se actualizan los datos...", true);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {

			String resultado = new String();
			String METHOD_NAME = "updatePaciente";
			String SOAP_ACTION = NAMESPACE + "/" + METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("jsonPaciente", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive) soapEnvelope
						.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			// Valido que tenga la informacion necesaria
			if ("1".equals(result)) {
				Toast.makeText(UpdatePaciente.this, "Informacion actualizada",
						Toast.LENGTH_LONG).show();
				finish();
			} else {
				Toast.makeText(UpdatePaciente.this,
						"Error al actualizar la informacion del paciente",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	class RemovePacienteBackground extends AsyncTask<Integer, Void, String> {

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(UpdatePaciente.this,
					"Clinica del Sur",
					"Espere mientras se elimina el paciente...", true);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Integer... params) {

			String resultado = new String();
			String METHOD_NAME = "removePaciente";
			String SOAP_ACTION = NAMESPACE + "/" + METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("pacienteId", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive) soapEnvelope
						.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			// Valido que tenga la informacion necesaria
			if ("1".equals(result)) {
				Toast.makeText(UpdatePaciente.this, "Eliminada correctamente",
						Toast.LENGTH_LONG).show();
				finish();
			} else {
				Toast.makeText(UpdatePaciente.this,
						"Error al eliminar pelicula", Toast.LENGTH_LONG).show();
			}
		}
	}

}
